package com.xiguanlezz.cn.server.codec;

import com.xiguanlezz.cn.common.Operation;
import com.xiguanlezz.cn.common.OperationResult;
import com.xiguanlezz.cn.common.RequestMessage;
import com.xiguanlezz.cn.common.ResponseMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @Author：习惯了种种
 * @CreateDate：2024/10/16 23:47
 * @Description：业务处理器实体类
 */
public class OrderServerProcessHandler extends SimpleChannelInboundHandler<RequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RequestMessage requestMessage) throws Exception {
        System.out.printf("接收到来自客户端的请求: %s\n", requestMessage.toString());

        // 此时接收到的是已经从ByteBuf解码后的requestMessage对象
        Operation messageBody = requestMessage.getMessageBody();

        // 1. 执行业务逻辑
        OperationResult operationResult = messageBody.execute();

        // 2. 组装响应对象
        ResponseMessage responseMessage = new ResponseMessage();
        responseMessage.setMessageHeader(requestMessage.getMessageHeader());
        responseMessage.setMessageBody(operationResult);

        // 3. 往对端发送数据
        /**
         * 如果使用ctx去写数据，会从当前handler开始往前广播出站事件，切记不要弄错encoder和业务逻辑handler的顺序
         * ctx.writeAndFlush(msg);
         */
        // pipeline的writeAndFlush(msg)方法会从尾部的TailContext一路往前传播
        ctx.pipeline().writeAndFlush(responseMessage);
    }
}
